package com.example.baselibrary.permission;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

public class PermissionHandler {

    private static final String PERMISSION_DENIED_MESSAGE_PRE = "您已拒绝了";
    private static final String PERMISSION_DENIED_MESSAGE_SUFF = "权限,无法使用此功能!";

    public boolean checkPermission(Activity activity, String permission) {
        if (ActivityCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        return false;
    }

    public void requestPermission(Activity activity, int requestCode, String permission) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
            String permissionChinese = getPermissionChinese(permission);
            new QMUIDialog.MessageDialogBuilder(activity)
                    .setMessage(PERMISSION_DENIED_MESSAGE_PRE
                            + permissionChinese + PERMISSION_DENIED_MESSAGE_SUFF)
                    .addAction("取消", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .addAction("申请", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            ActivityCompat.requestPermissions(activity, new String[] {permission}, requestCode);
                            dialog.dismiss();
                        }
                    })
                    .create(com.qmuiteam.qmui.R.style.QMUI_Dialog)
                    .show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[] {permission}, requestCode);
        }
    }

    private String getPermissionChinese(String permission) {
        switch (permission) {
            case Manifest.permission.CAMERA:
                return "相机拍照";
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
            case Manifest.permission.READ_EXTERNAL_STORAGE:
                return "文件读写";
            case Manifest.permission.ACCESS_FINE_LOCATION:
                return "位置获取";
        }
        return permission;
    }
}
